package cc.magicjson.tools.chain.processor.condition;

import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 条件处理器（支持链式组合），用于根据特定条件执行对应的处理逻辑
 * 支持链式回滚和链式回调
 *
 * @param <T> 处理的对象类型
 */
@SuppressWarnings("unused")
public class ConditionProcessor<T> {
    private static final Logger logger = Logger.getLogger(ConditionProcessor.class.getName()); // 日志记录器

    // 使用线程安全的队列存储处理器
    private final ConcurrentLinkedQueue<ConditionHandler<T>> handlers = new ConcurrentLinkedQueue<>();

    // 存储回滚处理器，与正向处理器一一对应
    private final ConcurrentLinkedQueue<RollbackHandler<T>> rollbackHandlers = new ConcurrentLinkedQueue<>();

    // 记录已添加的链，防止重复
    private final Set<ConditionChain<T>> addedChains = new HashSet<>();

    // 全局自增序列号，保证顺序执行
    private final AtomicLong sequence = new AtomicLong(0);

    // 是否启用优先级排序
    private boolean priorityEnabled;

    // 是否启用事务回滚功能
    private boolean rollbackEnabled = false;

    // 默认处理器（当所有条件都不匹配时执行）
    private Consumer<T> defaultHandler = t -> {};

    // 统一异常处理
    private BiConsumer<T, Exception> exceptionHandler = (t, e) ->
        logger.log(Level.SEVERE, "处理器异常: " + t, e);

    // 全局成功回调
    private Consumer<T> successCallback = t -> {};

    // 全局失败回调
    private BiConsumer<T, Exception> failureCallback = (t, e) -> {};

    // 记录执行过程中已成功执行的处理器，用于回滚
    private final ThreadLocal<Deque<RollbackHandler<T>>> executedHandlersForRollback =
        ThreadLocal.withInitial(LinkedList::new);

    /**
     * 处理目标对象，根据注册的条件执行匹配的处理器
     *
     * @param target 需要处理的对象
     * @return 处理后的对象，允许处理器修改对象状态
     */
    public T process(T target) {
        // 清理当前线程的回滚处理器记录
        if (rollbackEnabled) {
            executedHandlersForRollback.get().clear();
        }

        T result = target; // 创建局部变量跟踪处理结果

        try {
            // 获取排序后的处理器列表（按优先级和顺序号）
            List<ConditionHandler<T>> sortedHandlers = getSortedHandlers();
            boolean handlerExecuted = false; // 记录是否有处理器被执行

            // 遍历处理器列表
            for (ConditionHandler<T> handler : sortedHandlers) {
                try {
                    // 判断条件是否满足
                    if (handler.predicate.test(result)) {
                        // 在执行处理逻辑前，如果有回滚处理器，先注册它
                        if (rollbackEnabled && handler.rollbackHandler != null) {
                            executedHandlersForRollback.get().push(handler.rollbackHandler);
                        }

                        // 然后执行处理逻辑并获取返回值
                        T newResult = handler.consumer.apply(result);
                        if (newResult != null) {
                            result = newResult; // 更新处理结果
                        }

                        handlerExecuted = true;

                        // 如果该处理器要求匹配后终止，则退出循环
                        if (handler.stopOnMatch) break;
                    }
                } catch (Exception e) {
                    // 处理异常，并执行回滚操作
                    System.out.println("处理器异常: " + e.getMessage() + "，准备执行回滚");
                    result = handleExceptionWithRollback(result, e);
                    failureCallback.accept(result, e);
                    return result; // 异常情况下直接返回
                }
            }

            // 如果没有任何处理器匹配，则执行默认处理器
            if (!handlerExecuted) {
                defaultHandler.accept(result);
            }

            // 处理成功，调用成功回调
            successCallback.accept(result);
        } catch (Exception e) {
            result = handleExceptionWithRollback(result, e); // 处理外层异常
            failureCallback.accept(result, e);
        } finally {
            // 清理线程本地变量，防止内存泄漏
            if (rollbackEnabled) {
                executedHandlersForRollback.remove();
            }
        }

        return result;
    }

    /**
     * 异步处理目标对象
     *
     * @param target 需要处理的对象
     * @return 返回CompletableFuture对象
     */
    public CompletableFuture<T> processAsync(T target) {
        return CompletableFuture.supplyAsync(() -> {
            return process(target);
        });
    }

    /**
     * 执行回滚操作
     *
     * @param target 需要回滚的对象
     * @return 回滚后的对象
     */
    private T rollback(T target) {
        if (!rollbackEnabled) return target;

        T result = target;
        Deque<RollbackHandler<T>> handlers = executedHandlersForRollback.get();

        // 使用栈结构，确保按照LIFO顺序执行回滚（后进先出）
        while (!handlers.isEmpty()) {
            try {
                RollbackHandler<T> rollbackHandler = handlers.pop();
                T newResult = rollbackHandler.rollback.apply(result);
                if (newResult != null) {
                    result = newResult;
                }
            } catch (Exception e) {
                logger.log(Level.SEVERE, "回滚过程中发生异常", e);
                // 继续执行其他回滚操作，尽可能恢复系统状态
            }
        }

        return result;
    }

    /**
     * 处理异常并执行回滚
     *
     * @return 回滚后的对象
     */
    private T handleExceptionWithRollback(T target, Exception e) {
        try {
            // 先执行回滚
            T result = rollback(target);
            // 再执行异常处理
            exceptionHandler.accept(result, e);
            return result;
        } catch (Exception ex) {
            logger.log(Level.SEVERE, "异常处理器出错", ex);
            return target;
        }
    }

    //  批量添加多个 `ConditionChain<T>`
    public void addChains(Collection<ConditionChain<T>> chains) {
        for (ConditionChain<T> chain : chains) {
            addChain(chain);
        }
    }

    /**
     * 添加一个条件链到处理器中
     * 只添加未添加过的链，避免重复
     * @param chain 条件链
     */
    public void addChain(ConditionChain<T> chain) {
        // 避免重复添加
        if (addedChains.contains(chain)) return;
        // 记录已添加的链
        addedChains.add(chain);
        // 遍历链中的所有处理器并添加到队列
        chain.getHandlers().forEach(handler -> {
            long seqNum = sequence.getAndIncrement();
            handlers.add(new ConditionHandler<>(
                handler.priority,        // 继承链中定义的优先级
                seqNum, // 生成全局唯一的序列号
                handler.predicate,
                handler.consumer,
                handler.stopOnMatch,
                handler.rollbackHandler
            ));

            // 如果有回滚处理器，也添加到回滚队列中
            if (handler.rollbackHandler != null) {
                rollbackHandlers.add(new RollbackHandler<>(seqNum, handler.rollbackHandler.rollback));
            }
        });
    }

    /**
     * 直接添加一个处理条件
     *
     * @param priority 优先级
     * @param predicate 条件判断
     * @param action 处理逻辑
     * @param stop 是否在匹配后终止
     */
    public void addCondition(int priority, Predicate<T> predicate, Consumer<T> action, boolean stop) {
        handlers.add(new ConditionHandler<>(priority, sequence.getAndIncrement(), predicate, action, stop, null));
    }

    /**
     * 直接添加一个带回滚处理逻辑的处理条件
     */
    public void addCondition(int priority, Predicate<T> predicate, Function<T, T> action,
                             Function<T, T> rollback, boolean stop) {
        long seqNum = sequence.getAndIncrement();
        RollbackHandler<T> rollbackHandler = new RollbackHandler<>(seqNum, rollback);
        handlers.add(new ConditionHandler<>(priority, seqNum, predicate, action, stop, rollbackHandler));
        rollbackHandlers.add(rollbackHandler);
    }

    /**
     * 直接添加一个带回滚处理逻辑的处理条件
     * 提供明确类型标识的特殊方法
     */
    public void addAction(int priority, Predicate<T> predicate, Consumer<T> action,
                          Consumer<T> rollback, boolean stop) {
        long seqNum = sequence.getAndIncrement();
        // 转换Consumer为Function
        Function<T, T> actionFunc = t -> {
            action.accept(t);
            return t;
        };
        Function<T, T> rollbackFunc = t -> {
            rollback.accept(t);
            return t;
        };

        RollbackHandler<T> rollbackHandler = new RollbackHandler<>(seqNum, rollbackFunc);
        handlers.add(new ConditionHandler<>(priority, seqNum, predicate, actionFunc, stop, rollbackHandler));
        rollbackHandlers.add(rollbackHandler);
    }

    /**
     * 批量添加多个条件处理器
     *
     * @param conditionList 处理器列表
     */
    public void addConditions(List<ConditionHandler<T>> conditionList) {
        handlers.addAll(conditionList);
    }

    /**
     * 设置成功回调
     *
     * @param callback 成功回调函数
     */
    public void onSuccess(Consumer<T> callback) {
        this.successCallback = callback;
    }

    /**
     * 设置失败回调
     *
     * @param callback 失败回调函数
     */
    public void onFailure(BiConsumer<T, Exception> callback) {
        this.failureCallback = callback;
    }

    /**
     * 启用回滚功能
     */
    public void enableRollback(boolean enable) {
        this.rollbackEnabled = enable;
    }

    /**
     * 创建一个新的条件处理器构建器
     */
    public static <T> Builder<T> builder() {
        return new Builder<>();
    }

    /** 构建器模式，简化 `ConditionProcessor` 实例化 */
    public static class Builder<T> {
        private final ConditionProcessor<T> processor = new ConditionProcessor<>();

        public Builder<T> enablePriority(boolean enable) {
            processor.priorityEnabled = enable;
            return this;
        }

        public Builder<T> enableRollback(boolean enable) {
            processor.rollbackEnabled = enable;
            return this;
        }

        public Builder<T> defaultHandler(Consumer<T> handler) {
            processor.defaultHandler = handler;
            return this;
        }

        public Builder<T> exceptionHandler(BiConsumer<T, Exception> handler) {
            processor.exceptionHandler = handler;
            return this;
        }

        public Builder<T> onSuccess(Consumer<T> callback) {
            processor.successCallback = callback;
            return this;
        }

        public Builder<T> onFailure(BiConsumer<T, Exception> callback) {
            processor.failureCallback = callback;
            return this;
        }

        public Builder<T> addChain(ConditionChain<T> chain) {
            processor.addChain(chain);
            return this;
        }

        public Builder<T> addChains(Collection<ConditionChain<T>> chains) {
            processor.addChains(chains);
            return this;
        }

        public ConditionProcessor<T> build() {
            return processor;
        }
    }

    /** 条件链 */
    public static class ConditionChain<T> {
        private final List<ConditionHandler<T>> handlers = new ArrayList<>();
        private int currentPriority;

        /**
         * 创建一个新的条件链
         */
        public static <T> ConditionChain<T> of() {
            return new ConditionChain<>();
        }

        /**
         * 设置优先级
         */
        public ConditionChain<T> priority(int priority) {
            this.currentPriority = priority;
            return this;
        }

        /**
         * 添加一个条件处理器 (支持返回值)
         */
        public ConditionChain<T> when(Predicate<T> predicate, Function<T, T> action, boolean stop) {
            handlers.add(new ConditionHandler<>(currentPriority, 0, predicate, action, stop, null));
            return this;
        }

        /**
         * 添加一个带回滚功能的条件处理器 (支持返回值)
         */
        public ConditionChain<T> when(Predicate<T> predicate, Function<T, T> action, Function<T, T> rollback, boolean stop) {
            RollbackHandler<T> rollbackHandler = new RollbackHandler<>(0, rollback);
            handlers.add(new ConditionHandler<>(currentPriority, 0, predicate, action, stop, rollbackHandler));
            return this;
        }

        /**
         * 添加一个带回滚功能的条件处理器 (原始Consumer版本)
         */
        public ConditionChain<T> when(Predicate<T> predicate, Consumer<T> action, Consumer<T> rollback, boolean stop) {
            Function<T, T> actionFunc = t -> {
                action.accept(t);
                return t;
            };
            Function<T, T> rollbackFunc = t -> {
                rollback.accept(t);
                return t;
            };
            RollbackHandler<T> rollbackHandler = new RollbackHandler<>(0, rollbackFunc);
            handlers.add(new ConditionHandler<>(currentPriority, 0, predicate, actionFunc, stop, rollbackHandler));
            return this;
        }

        // 向下兼容的Consumer版本方法，修复when的Consumer重载
        public ConditionChain<T> when(Predicate<T> predicate, Consumer<T> action, boolean stop) {
            Function<T, T> actionFunc = t -> {
                action.accept(t);
                return t;
            };
            handlers.add(new ConditionHandler<>(currentPriority, 0, predicate, actionFunc, stop, null));
            return this;
        }

        public ConditionChain<T> whenMatch(Predicate<T> predicate, Consumer<T> action) {
            return when(predicate, action, false);
        }

        /**
         * 新增明确类型的Function版本，帮助解决Lambda推断问题
         */
        public <R extends T> ConditionChain<T> whenMatchWithRollback(
            Predicate<T> predicate,
            java.util.function.Function<T, R> action,
            java.util.function.Function<T, R> rollback) {
            return when(predicate,
                t -> (T)action.apply(t),
                t -> (T)rollback.apply(t),
                false);
        }

        /**
         * 新增明确的Order对象处理方法，处理泛型问题
         */
        public ConditionChain<T> whenMatchWithRollback(
            Predicate<T> predicate,
            java.util.function.UnaryOperator<T> action,
            java.util.function.UnaryOperator<T> rollback) {
            return when(predicate, action, rollback, false);
        }

        public ConditionChain<T> whenStop(Predicate<T> predicate, Consumer<T> action) {
            return when(predicate, action, true);
        }

        public ConditionChain<T> whenStopWithRollback(Predicate<T> predicate, Function<T, T> action, Function<T, T> rollback) {
            return when(predicate, action, rollback, true);
        }

        public ConditionChain<T> whenStopWithRollback(Predicate<T> predicate, Consumer<T> action, Consumer<T> rollback) {
            Function<T, T> actionFunc = t -> {
                action.accept(t);
                return t;
            };
            Function<T, T> rollbackFunc = t -> {
                rollback.accept(t);
                return t;
            };
            return when(predicate, actionFunc, rollbackFunc, true);
        }

        /**
         * 获取所有处理器（不可修改）
         */
        List<ConditionHandler<T>> getHandlers() {
            return Collections.unmodifiableList(handlers);
        }
    }

    /**
     * 获取排序后的处理器列表
     */
    private List<ConditionHandler<T>> getSortedHandlers() {
        List<ConditionHandler<T>> copy = new ArrayList<>(handlers);

        if (priorityEnabled) {
            // 按优先级降序排列，优先级相同时按顺序号排序
            copy.sort(Comparator
                .comparingInt((ConditionHandler<T> h) -> h.priority)
                .reversed()
                .thenComparingLong(h -> h.sequence)
            );
        } else {
            // 仅按顺序号排序（先注册的先执行）
            copy.sort(Comparator.comparingLong(h -> h.sequence));
        }

        return copy;
    }

    /**
     * 统一异常处理
     */
    private void handleException(T target, Exception e) {
        try {
            exceptionHandler.accept(target, e);
        } catch (Exception ex) {
            logger.log(Level.SEVERE, "异常处理器出错", ex);
        }
    }

    /**
     * 条件处理器实体
     */
    public static class ConditionHandler<T> {
        final int priority;            // 优先级
        final long sequence;           // 顺序号
        final Predicate<T> predicate;  // 条件判断
        final Function<T, T> consumer; // 处理逻辑，改为Function接口支持返回值
        final boolean stopOnMatch;     // 是否匹配后终止
        final RollbackHandler<T> rollbackHandler; // 回滚处理器

        public ConditionHandler(int priority, long sequence, Predicate<T> predicate,
                                Function<T, T> consumer, boolean stopOnMatch, RollbackHandler<T> rollbackHandler) {
            this.priority = priority;
            this.sequence = sequence;
            this.predicate = predicate;
            this.consumer = consumer;
            this.stopOnMatch = stopOnMatch;
            this.rollbackHandler = rollbackHandler;
        }

        // 添加适配Consumer的构造器，向下兼容
        public ConditionHandler(int priority, long sequence, Predicate<T> predicate,
                                Consumer<T> consumer, boolean stopOnMatch, RollbackHandler<T> rollbackHandler) {
            this.priority = priority;
            this.sequence = sequence;
            this.predicate = predicate;
            this.consumer = t -> {
                consumer.accept(t);
                return t;  // 无返回值时保持原对象
            };
            this.stopOnMatch = stopOnMatch;
            this.rollbackHandler = rollbackHandler;
        }
    }

    /**
     * 回滚处理器实体
     */
    public static class RollbackHandler<T> {
        final long sequence;           // 顺序号，与对应的条件处理器保持一致
        final Function<T, T> rollback; // 回滚逻辑，改为Function

        public RollbackHandler(long sequence, Function<T, T> rollback) {
            this.sequence = sequence;
            this.rollback = rollback;
        }
    }

    /**
     * 辅助方法：根据序列号查找回滚处理器
     */
    private RollbackHandler<T> findRollbackHandler(long sequence) {
        for (RollbackHandler<T> handler : rollbackHandlers) {
            if (handler.sequence == sequence) {
                return handler;
            }
        }
        return null;
    }
}
